package utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import ognl.Ognl;
import ognl.OgnlException;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Project:TODO ADD PROJECT NAME
 * Modify Information:
 * ================================================================
 * Author         Date           Description
 * ------------   ----------      --------------------------------
 * songyf        2023/5/18         TODO:
 * ================================================================
 * Copyright (wildcard) 银联商务股份有限公司 www.chinaums.com
 */
public class OgnlTest {

    @Test
    public void f() {
        String[] a = new String[2];
        Object[] b = a;
        a[0] = "hi";
        b[1] = Integer.valueOf(42);
    }

    public static void main(String[] args) throws OgnlException {
        Map<String, Object> map = new HashMap<>();
        map.put("STRING", "Enum");

        User3 entity = new User3();
        entity.setWorkflowDefinitionKey("Enum");
        Object[] objArr = new Object[] {new Object(), entity, entity};
        map.put("entity", objArr);

        ArrayList<User3> strings = new ArrayList<>();
        strings.add(new User3("a", "Enum"));
        strings.add(new User3("b", "Enum"));
        strings.add(new User3("b", "Enum"));
        strings.add(new User3("b", "ddd"));
        map.put("array", strings);

        Object value1 = Ognl.getValue("#this.entity", map);

        String expression = "#this.array[*].workflowDefinitionKey";
        wildcard(expression, map);

        Object value2 = Ognl.getValue("#this.array", map);



        Ognl.setValue("#this[1].workflowDefinitionKey", objArr, "New Name");
        System.out.println(entity);
    }


    private static int getLength(Object o){
        if (o instanceof List){
            int size = ((List<?>) o).size();
            return size;
        }
        if (o instanceof Object[]){
            int length = ((Object[]) o).length;
            return length;
        }
        return 0;
    }

    @SneakyThrows
    private static void wildcard(String expression, Map map){
        //没有* 直接处理
        int index = expression.indexOf("*");
        if (index<=0){
            System.out.println(expression);
            String value = (String) Ognl.getValue(expression, map);
            Ognl.setValue(expression, map, value+"add");
            return ;
        }

        //计算父节点的长度n
        String parentExpre = expression.substring(0, index-1);
        int length = getLength(Ognl.getValue(parentExpre, map));
        for (int i = 0; i < length; i++) {
            String newExpression = expression.substring(0, index) + i + expression.substring(index+1);
            wildcard(newExpression, map);
        }
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class User3 {
    private String id;
    private String workflowDefinitionKey;
}
